// 压缩图片
export function compressImage({ file, config = {}, fileName }) {
    const read = new FileReader()
    read.readAsDataURL(file)
    return new Promise(function (resolve) {
        read.onload = function (e) {
            let img = new Image()
            img.src = e.target.result
            img.onload = function () {
                // 默认按比例压缩
                let w = config.width || img.width
                let h = config.height || img.height
                const maxWidth = 800
                if (w > maxWidth) {
                    const scare = maxWidth / w
                    w *= scare
                    h *= scare
                }
                // 生成canvas
                let canvas = document.createElement('canvas')
                let ctx = canvas.getContext('2d')
                let base64
                // 创建属性节点
                canvas.setAttribute('width', w)
                canvas.setAttribute('height', h)
                ctx.drawImage(this, 0, 0, w, h)
                base64 = canvas.toDataURL(file['type'], config.quality || 0.5)
                let finalFile = dataURLtoFile(base64, fileName)
                let fileBinary = dataURLtoBlob(base64, fileName)
                // console.log('base转化为file', finalFile);
                resolve({ finalFile, fileBinary })
            }
        }
    })
}
// 将base64转为二进制
function dataURLtoBlob(dataurl, fileName) {
    let arr = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    let blobObj = new Blob([u8arr], { type: mime })
    return {
        fileName,
        blobUrl: URL.createObjectURL(blobObj)
    }
}

// 将base64编码转回file文件  
function dataURLtoFile(dataurl, fileName) {
    let arr = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    let file = new File([u8arr], { type: mime })
    return new File([u8arr], fileName, {
        type: mime
    });
    // return {
    //     fileName,
    //     file
    // }
}